package com.jinzhi.jzweb.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.type.EnumErrorCode;
import com.jinzhi.common.utils.EhCacheUtil;
import com.jinzhi.common.utils.Result;
import com.jinzhi.jzweb.domain.ExaminationGradingDO;
import com.jinzhi.jzweb.domain.ItemBankDO;
import com.jinzhi.jzweb.pojo.ErroeDownVo;
import com.jinzhi.jzweb.pojo.ErrorCodeVo;
import com.jinzhi.jzweb.pojo.ExaminationGradingVo;
import com.jinzhi.jzweb.service.ExaminationGradingService;
import com.jinzhi.jzweb.service.ItemBankService;
import com.jinzhi.jzweb.utils.EasyPoiUtil;
import com.jinzhi.jzweb.utils.IdCardUtil;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * 
 * <pre>
 * 技能考试评分信息表
 * </pre>
 * <small> 2020-06-05 09:41:09 | lance</small>
 */
@Controller
@RequestMapping("/jzweb/examinationGrading")
public class ExaminationGradingController extends BaseController {
	@Autowired
	private ExaminationGradingService examinationGradingService;
	@Autowired
	private ItemBankService itemBankService;
	@Autowired
	private UserService userService;

	@GetMapping("/{id}")
	@RequiresPermissions("jzweb:examinationGrading:examinationGrading")
	String ExaminationGrading(@PathVariable("id") Long id,Model model){
		model.addAttribute("ibankId",id);
	    return "jzweb/examinationGrading/examinationGrading";
	}
	
	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("jzweb:examinationGrading:examinationGrading")
	public Result<Page<ExaminationGradingDO>> list(ExaminationGradingDO examinationGradingDTO){
		Wrapper<ExaminationGradingDO> wrapper = new EntityWrapper<ExaminationGradingDO>().orderBy("number", true);
		if (examinationGradingDTO.getIbankId() != null){
			wrapper.eq("ibank_id",examinationGradingDTO.getIbankId());
		}
		if (examinationGradingDTO.getAssBlock() != null){
			wrapper.like("ass_block",examinationGradingDTO.getAssBlock());
		}

		Page<ExaminationGradingDO> page = examinationGradingService.selectPage(getPage(ExaminationGradingDO.class), wrapper);
		List list = new ArrayList();
		for (int i = 0; i < page.getRecords().size(); i++) {
			ExaminationGradingDO obj = (ExaminationGradingDO) page.getRecords().get(i);
			if (obj.getCreaterId() != null){
				UserDO userDO = userService.selectById(obj.getCreaterId());
				if (userDO != null) {
					obj.setCreaterName(userDO.getName());
				}
			}
			if (obj.getUpdaterId() != null){
				UserDO userDO = userService.selectById(obj.getUpdaterId());
				if (userDO != null) {
					obj.setUpdaterName(userDO.getName());
				}
			}
			if (obj.getIbankId() != null){
				ItemBankDO itemBankDO = itemBankService.selectById(obj.getIbankId());
				if (itemBankDO != null) {
					obj.setIbankName(itemBankDO.getTopicContent());
				}
			}
			list.add(obj);
		}
		page.setRecords(list);
        return Result.ok(page);
	}
	
	@GetMapping("/add")
	@RequiresPermissions("jzweb:examinationGrading:add")
	String add(Model model,String pid){
		model.addAttribute("pid",pid);
		ItemBankDO itemBankDO = itemBankService.selectById(pid);
		if(itemBankDO != null){
			model.addAttribute("name",itemBankDO.getTopicContent());
		}else{
			model.addAttribute("name",null);
		}
	    return "jzweb/examinationGrading/add";
	}

	@GetMapping("/edit/{id}")
	@RequiresPermissions("jzweb:examinationGrading:edit")
	String edit(@PathVariable("id") Long id,Model model){
		ExaminationGradingDO examinationGrading = examinationGradingService.selectById(id);
		ItemBankDO itemBankDO = itemBankService.selectById(examinationGrading.getIbankId());
		if(itemBankDO != null){
			model.addAttribute("name",itemBankDO.getTopicContent());
		}else{
			model.addAttribute("name",null);
		}
		model.addAttribute("examinationGrading", examinationGrading);
	    return "jzweb/examinationGrading/edit";
	}

	@GetMapping("/info/{id}")
	@RequiresPermissions("jzweb:examinationGrading:examinationGrading")
	String info(@PathVariable("id") Long id, Model model) {
		ExaminationGradingDO examinationGrading = examinationGradingService.selectById(id);
		if (examinationGrading != null) {
			if (examinationGrading.getCreaterId() != null){
				UserDO userDO = userService.selectById(examinationGrading.getCreaterId());
				if (userDO != null) {
					examinationGrading.setCreaterName(userDO.getName());
				}
			}
			if (examinationGrading.getUpdaterId() != null){
				UserDO userDO = userService.selectById(examinationGrading.getUpdaterId());
				if (userDO != null) {
					examinationGrading.setUpdaterName(userDO.getName());
				}
			}
			if (examinationGrading.getIbankId() != null){
				ItemBankDO itemBankDO = itemBankService.selectById(examinationGrading.getIbankId());
				if (itemBankDO != null) {
					examinationGrading.setIbankName(itemBankDO.getTopicContent());
				}
			}
		}
		model.addAttribute("examinationGrading", examinationGrading);
		return "jzweb/examinationGrading/info";
	}
	
	@Log("添加技能考试评分信息表")
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("jzweb:examinationGrading:add")
	public Result<String> save( ExaminationGradingDO examinationGrading){
		//根据题库id、考核块、考核内容、考核站点判断是否重复，一个考核块可能有多个考核内容，一个考核内容可能有多个考核站点
		ExaminationGradingDO examinationGradingDO = examinationGradingService.findOneByKv("ibank_id",examinationGrading.getIbankId(),
				"ass_content",examinationGrading.getAssContent(),"ass_block",examinationGrading.getAssBlock(), "acc_point",examinationGrading.getAccPoint());
		if (examinationGradingDO != null) {
			return Result.fail("标准已存在，请检查");
		} else {
			ExaminationGradingDO examinationGradingDO1 = examinationGradingService
					.findOneByKv("ibank_id",examinationGrading.getIbankId(),"number",examinationGrading.getNumber());
			if(examinationGradingDO1 != null){
				return Result.fail("标准编号重复，请修改");
			}
			examinationGrading.setCreaterId(this.getUserId());
			examinationGrading.setUpdaterId(this.getUserId());
			boolean bbc = examinationGradingService.insert(examinationGrading);
			if(!bbc){
				return Result.fail();
			}
			return Result.ok();
		}
	}
	
	@Log("修改技能考试评分信息表")
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("jzweb:examinationGrading:edit")
	public Result<String>  update( ExaminationGradingDO examinationGrading){
		//根据题库id、考核块、考核内容、考核站点判断是否重复，一个考核块可能有多个考核内容，一个考核内容可能有多个考核站点
		List<ExaminationGradingDO> examinationGradingDOs = examinationGradingService.findByKv("ibank_id",examinationGrading.getIbankId(),
				"ass_content",examinationGrading.getAssContent(),"ass_block",examinationGrading.getAssBlock(), "acc_point",examinationGrading.getAccPoint());
		if (examinationGradingDOs != null && examinationGradingDOs.size() > 0) {
			if(examinationGradingDOs.size() == 1){
				if(examinationGradingDOs.get(0).getId().equals(examinationGrading.getId())){
					List<ExaminationGradingDO> examinationGradingDO1 = examinationGradingService
							.findByKv("ibank_id",examinationGrading.getIbankId(),"number",examinationGrading.getNumber());
					if(examinationGradingDO1 != null && examinationGradingDO1.size() > 0){
						if(examinationGradingDO1.size() == 1){
							if(examinationGradingDO1.get(0).getId().equals(examinationGrading.getId())){
								examinationGrading.setUpdaterId(this.getUserId());
								boolean update = examinationGradingService.updateById(examinationGrading);
								return update ? Result.ok() : Result.fail();
							}
						}
						return Result.fail("标准编号重复，请修改");
					}else{
						examinationGrading.setUpdaterId(this.getUserId());
						boolean update = examinationGradingService.updateById(examinationGrading);
						return update ? Result.ok() : Result.fail();
					}
				}
			}
			return Result.fail("标准已存在，请检查");
		} else {
			List<ExaminationGradingDO> examinationGradingDO1 = examinationGradingService
					.findByKv("ibank_id",examinationGrading.getIbankId(),"number",examinationGrading.getIbankId());
			if(examinationGradingDO1 != null && examinationGradingDO1.size() > 0){
				if(examinationGradingDO1.size() == 1){
					if(examinationGradingDO1.get(0).getId().equals(examinationGrading.getId())){
						examinationGrading.setUpdaterId(this.getUserId());
						boolean update = examinationGradingService.updateById(examinationGrading);
						return update ? Result.ok() : Result.fail();
					}
				}
				return Result.fail("标准编号重复，请修改");
			}else{
				examinationGrading.setUpdaterId(this.getUserId());
				boolean update = examinationGradingService.updateById(examinationGrading);
				return update ? Result.ok() : Result.fail();
			}
		}
	}
	
	@Log("删除技能考试评分信息表")
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("jzweb:examinationGrading:remove")
	public Result<String>  remove( Long id){
		examinationGradingService.deleteById(id);
        return Result.ok();
	}
	
	@Log("批量删除技能考试评分信息表")
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("jzweb:examinationGrading:batchRemove")
	public Result<String>  remove(@RequestParam("ids[]") Long[] ids){
		examinationGradingService.deleteBatchIds(Arrays.asList(ids));
		return Result.ok();
	}

	/**
	 * 下载导入模板
	 * @author kl
	 * @param response
	 */
	@RequestMapping("/downloadImportTemplate")
	@RequiresPermissions("jzweb:examinationGrading:import")
	@ResponseBody
	public void downloadImportTemplate(HttpServletResponse response) {
		List<ExaminationGradingVo> list = new LinkedList<>();
		//导出操作
		EasyPoiUtil.exportExcel(list, "技能考试评分信息导入模板", "技能考试评分信息导入模板", ExaminationGradingVo.class, "技能考试评分信息导入模板", response);
	}

	/**
	 * 题目信息导入
	 * @author kl
	 * @param file excel文件
	 */
	@Log("题目信息导入")
	@PostMapping("/import")
	@ResponseBody
	@Transactional
	@RequiresPermissions("jzweb:examinationGrading:import")
	public Result<?> importExcel(@RequestParam("file") MultipartFile file, Long ibankId) {
		//---------------------------------检测导入信息及条件-----------------------------------------
		//第一步--判断文件格式
		if (!"application/vnd.ms-excel".equals(file.getContentType())) {
			return Result.fail("文件格式错误，请选择.xls文件");
		}

		//第二步--解析文件获得数据
		List<ExaminationGradingVo> list = EasyPoiUtil.importExcel(file, 1, 1, ExaminationGradingVo.class);
		if (list.size() == 0) {
			return Result.fail("Excel数据为空，请完善");
		}

		List<Integer> integers = examinationGradingService.numbersList(ibankId);

		//---------------------------------验证数据并导入-----------------------------------------
		//数据该表第三行，第一行标题，第二行表头
		int startRow = 3;
		int cout = 1;//错误信息计数
		List<ExaminationGradingDO> gradingDOList = new ArrayList<>();
		List<ErrorCodeVo> list1 = new ArrayList<>();
		for (int i = 0; i < list.size(); i++) {
			StringBuilder sb = new StringBuilder();
			//第一步验证是否存在空值
			if (StringUtils.isBlank(list.get(i).getNumber())) {
				sb.append("第" + (i + startRow) + "行评分标准序号未填写，请完善！" + ";");
			} else {
				if (StringUtils.isBlank(list.get(i).getAssBlock())) {
					sb.append("第" + (i + startRow) + "行考核块未填写，请完善！" + ";");
				} else {
					if (StringUtils.isBlank(list.get(i).getAssContent())) {
						sb.append("第" + (i + startRow) + "行考核内容未填写，请完善！" + ";");
					} else {
						if (StringUtils.isBlank(list.get(i).getAccPoint())) {
							sb.append("第" + (i + startRow) + "行考核点未填写，请完善！" + ";");
						} else {
							if (StringUtils.isBlank(list.get(i).getScore())) {
								sb.append("第" + (i + startRow) + "行分值未填写，请完善！" + ";");
							} else {
								if (StringUtils.isBlank(list.get(i).getRatingClaim())) {
									sb.append("第" + (i + startRow) + "行评分要求未填写，请完善！" + ";");
								} else {
									if (!IdCardUtil.isNumeric(list.get(i).getNumber())) {
										sb.append("第" + (i + startRow) + "行评分标准序号不为数字，请修改！" + ";");
									}else{
										if (!IdCardUtil.isNumeric(list.get(i).getScore())) {
											sb.append("第" + (i + startRow) + "行分值不为数字，请修改！" + ";");
										}else{
											//第二步排重验证（自身比较）
											for (int j = 0; j < list.size(); j++) {
												if (i != j) {
													if (list.get(i).getNumber().trim().equals(list.get(j).getNumber().trim())) {
														sb.append("第" + (i + startRow) + "行跟第" + (j + startRow) + "行评分标准序号重复，重复值：" + list.get(i).getNumber().trim() + ";");
													}
													if ((list.get(i).getAssBlock().trim().equals(list.get(j).getAssBlock().trim()))
															&& (list.get(i).getAssContent().trim().equals(list.get(j).getAssContent().trim()))
															&& (list.get(i).getAccPoint().trim().equals(list.get(j).getAccPoint().trim()))
													) {
														sb.append("第" + (i + startRow) + "行跟第" + (j + startRow) + "行考核站点重复，重复值：" + list.get(i).getAccPoint().trim() + ";");
													}
												}
											}

											//第三步排重验证（和数据库比较），根据题库id、考核块、考核内容、考核站点判断
											ExaminationGradingDO examinationGradingDO = examinationGradingService
													.findOneByKv("ibank_id",ibankId, "ass_content",list.get(i).getAssContent(),
															"ass_block",list.get(i).getAssBlock(), "acc_point",list.get(i).getAccPoint());
											if (examinationGradingDO != null) {
												sb.append("第" + (i + startRow) + "行评分标准已存在，请检查！" + ";");
											} else {
												boolean bcc = true;
												if(integers != null && integers.size() > 0){
													if(integers.contains(Integer.parseInt(list.get(i).getNumber()))){
														bcc = false;
														sb.append("第" + (i + startRow) + "行评分标准序号已存在，请检查！" + ";");
													}
												}

												if(bcc){
													ExaminationGradingDO examinationGradingDO1 = new ExaminationGradingDO();
													examinationGradingDO1.setIbankId(ibankId);//题目id
													examinationGradingDO1.setNumber(Integer.parseInt(list.get(i).getNumber()));//评分标准序号
													examinationGradingDO1.setAssBlock(list.get(i).getAssBlock());//考核块
													examinationGradingDO1.setAssContent(list.get(i).getAssContent());//考核内容
													examinationGradingDO1.setAccPoint(list.get(i).getAccPoint());//考核站点
													examinationGradingDO1.setScore(Integer.parseInt(list.get(i).getScore()));//分值
													examinationGradingDO1.setRatingClaim(list.get(i).getRatingClaim());//评分要求
													examinationGradingDO1.setState(0);//默认正常
													examinationGradingDO1.setCreaterId(this.getUserId());//创建人id
													examinationGradingDO1.setUpdaterId(this.getUserId());//修改人id

													gradingDOList.add(examinationGradingDO1);
													integers.add(Integer.parseInt(list.get(i).getNumber()));
												}

											}

										}
									}
								}
							}
						}
					}
				}
			}


			if (sb.length() > 0) {
				ErrorCodeVo errorCodeVo = new ErrorCodeVo();
				errorCodeVo.setSeq(cout);
				cout += 1;
				errorCodeVo.setErrorCode(sb.toString());
				list1.add(errorCodeVo);
			}
		}

		if (list1.size() == 0) {
			boolean c = examinationGradingService.insertBatch(gradingDOList, gradingDOList.size());
			if (c) {
				return Result.ok("成功导入" + list.size() + "条数据");
			} else {
				return Result.fail("技能考试评分信息导入错误，请稍后重试或联系管理员");
			}
		} else {
			JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(list1));
			//将list1存到缓存中
			EhCacheUtil.put("examinationGrading" + this.getUserId(), jsonArray);
			return Result.build(EnumErrorCode.FileImportError.getCode(), EnumErrorCode.FileImportError.getMsg());
		}
	}

	/**
	 * 导出错误信息
	 *
	 * @param request
	 * @param response
	 * @throws Exception
	 * @author kl
	 */
	@Log("导出错误信息")
	@GetMapping("/importError")
	@ResponseBody
	@Transactional
	@RequiresPermissions("jzweb:examinationGrading:import")
	public void download(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 告诉浏览器用什么软件可以打开此文件
		response.setHeader("content-Type", "application/vnd.ms-excel");
		// 下载文件的默认名称
		response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("技能考试评分信息导入错误信息", "UTF-8") + ".xls");
		//编码
		response.setCharacterEncoding("UTF-8");
		String jsonArray = EhCacheUtil.get("examinationGrading" + this.getUserId()).toString();
		JSONArray arrayList = JSONArray.parseArray(jsonArray);
		//转换为目标对象list
		List<ErroeDownVo> groupList = JSONObject.parseArray(arrayList.toJSONString(), ErroeDownVo.class);
		Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), ErroeDownVo.class, groupList);
		workbook.write(response.getOutputStream());
	}
	
}
